const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    planId: '',
    plan: null,
    processList: [],
    userList: [],
    processListWithAllocation: [],
    allocations: [],
    loading: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/allocate-production-plan/allocate-production-plan')) {
      return
    }
    
    if (options.planId) {
      this.setData({
        planId: options.planId
      })
      this.loadAllocationData()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载分配数据
  loadAllocationData() {
    this.setData({ loading: true })
    
    app.request({
      url: '/allocateProductionPlan',
      method: 'GET',
      data: { plan_id: this.data.planId }
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        const data = res.data
        console.log('分配数据加载成功:', data)
        console.log('用户列表:', data.userList)
        
        // 将userList对象转换为数组格式
        const userListArray = data.userList ? Object.keys(data.userList).map(id => ({
          id: parseInt(id),
          username: data.userList[id],
          nickname: data.userList[id]
        })) : []
        
        // 将processListWithAllocation对象转换为数组格式
        const processListWithAllocationArray = data.processListWithAllocation ? 
          Object.keys(data.processListWithAllocation).map(processId => {
            const process = data.processListWithAllocation[processId]
            const totalQuantity = process.total_quantity || 0
            const allocatedQuantity = process.allocated_quantity || 0
            const percentage = totalQuantity > 0 ? Math.round((allocatedQuantity / totalQuantity) * 100) : 0
            
            return {
              id: parseInt(processId),
              name: process.name,
              total_quantity: totalQuantity,
              allocated_quantity: allocatedQuantity,
              remaining_quantity: process.remaining_quantity,
              percentage: percentage
            }
          }) : []
        
        console.log('转换后的用户列表:', userListArray)
        console.log('转换后的工序分配列表:', processListWithAllocationArray)
        
        this.setData({
          plan: data.plan,
          processList: data.processList || [],
          userList: userListArray,
          processListWithAllocation: processListWithAllocationArray
        })
        
        wx.setNavigationBarTitle({
          title: '分配工序 - ' + (data.plan.plan_name || '生产计划')
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载分配数据失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 测试方法
  testMethod() {
    console.log('测试方法被调用')
  },

  // 分配工序
  allocateProcess(e) {
    const process = e.currentTarget.dataset.process
    if (!process) return
    
    // 跳转到专门的分配页面
    wx.navigateTo({
      url: `/pages/allocate-process/allocate-process?planId=${this.data.planId}&processId=${process.id}`
    })
  },


  // 跳转到批量分配
  goToBatchAllocate() {
    wx.showModal({
      title: '批量分配',
      content: '批量分配功能正在开发中，请使用单个工序分配功能',
      showCancel: false,
      confirmText: '知道了'
    })
  },

  // 查看现有分配
  viewExistingAllocations() {
    // 跳转到生产计划详情页面
    wx.navigateTo({
      url: `/pages/production-plan-detail/production-plan-detail?planId=${this.data.planId}`
    })
  }
})
